<?php

namespace backend\controllers;

use bc\controller\BackendController;
use bc\model\zsmm\RegisterModel;

class RegisterController extends BackendController
{
	
	public function actionIndex()
	{
		 
		$default_start_time_str = strtotime('-7 day');
		$default_start_time = date('Y-m-d', $default_start_time_str);
		 
		$default_end_time_str = strtotime('-1 day');
		$default_end_time = date('Y-m-d', $default_end_time_str);
		 
		$start_time = $this->get('start_time', '');
		$end_time = $this->get('end_time', '');
		 
		 
		$start_time = $start_time ? $start_time : $default_start_time;
		$end_time = $end_time ? $end_time : $default_end_time;
		 
		$dates = $this->showDates($start_time, $end_time);
		$view['dates'] = json_encode($dates);
		 
		
		$model = new RegisterModel();
		$data = $model->getStatistics($start_time, $end_time);
		 
		$json_data = $this->arrangeDate($dates, $data);
		$view['json_data'] = $json_data;
		 
		$view['list'] = $data;
		$view['start_time'] = $start_time;
		$view['end_time'] = $end_time;
		 
		return $this->render('index', $view);
	}
	
	
	/**
	 *
	 * @param string $start
	 * @param string $end
	 */
	protected function showDates($start, $end)
	{
		$list = [];
		while ($end >= $start)
		{
			$list[] = $end;
			$end = strtotime('-1 day', strtotime($end));
			$end = date('Y-m-d', $end);
	
		}
		$list = array_reverse($list);
		return $list;
	}
	
	/**
	 * 按照一定格式整理数据
	 * @param array $date
	 * @param json $data
	 */
	protected function arrangeDate($date, $data)
	{
		$list = [];
		foreach ($date as $row)
		{
			$tmp['date'] = $row;
			$tmp['total'] = 0;
			foreach ($data as $item)
			{
				if($row == $item['date'])
				{
					$tmp['total'] = $item['total'];
				}
			}
			$list[] = $tmp['total'];
		}
		 
		return json_encode($list);
	}
}

